package com.bwei.like.mynewstop.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.bwei.like.mynewstop.utils.CommonUtils;

/**
 * Created by LiKe on 2016/11/14.
 */
public class LetterView extends View {
    private String[] letters = {"#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"};
    private int singleHeight;
    private int height;
    private int width;
    private String lastCity = "";
    private OnLetterChangeListener onLetterChangeListener;

    public LetterView(Context context) {
        super(context);
    }

    public LetterView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LetterView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取控件的宽高
        height = this.getHeight();
        width = this.getWidth();
        //计算出每个字母所占的高度
        singleHeight = height / letters.length;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setTextSize(CommonUtils.dip2px(15));
        paint.setAntiAlias(true);
        //绘制
        for (int i = 0; i < letters.length; i++) {
            //测量出字母所在的x轴的中心点
            int x = (int) (width/2 - (paint.measureText(letters[i])/2));
            int y =  (int) (singleHeight * (i + 1));
            canvas.drawText(letters[i],x,y,paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:

                int y = (int) (event.getY() / height * letters.length);
                String letter = letters[y];
                if (!lastCity.equals(letter)){
                   // Toast.makeText(getContext(), "点击了"+letter, Toast.LENGTH_SHORT).show();
                    //调用接口中抽象方法，
                    onLetterChangeListener.setOnLetterChange(letter);
                    lastCity = letter;
                }
                break;

            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                lastCity = "";
                break;
        }

        return true;

    }

    //定义一个设置监听方法，参数为接口
    public void setOnChangeListener(OnLetterChangeListener onLetterChangeListener) {
        this.onLetterChangeListener = onLetterChangeListener;
    }

    //自定义接口
    public interface OnLetterChangeListener{
        public void setOnLetterChange(String s);
    }
}
